import 'package:flutter/material.dart';
import 'package:qaun_ni_dev/pages/login.dart';
import 'package:qaun_ni_dev/provider/active_provider.dart';
import 'package:qaun_ni_dev/provider/admin_provide.dart';
import 'package:qaun_ni_dev/provider/appUserProvider.dart';
import 'package:qaun_ni_dev/provider/attributeProvide.dart';
import 'package:qaun_ni_dev/provider/brush_provider.dart';
import 'package:qaun_ni_dev/provider/gift_provider.dart';
import 'package:qaun_ni_dev/provider/header_portrait_provider.dart';
import 'package:qaun_ni_dev/provider/loginProvider.dart';
import 'package:qaun_ni_dev/provider/real_name_provider.dart';
import 'package:qaun_ni_dev/provider/report_provider.dart';
import 'package:qaun_ni_dev/provider/rongImProvider.dart';
import 'package:qaun_ni_dev/provider/temp_provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart' as prefix ;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'im/util/event_bus.dart';
import 'router.dart';
import 'package:provider/provider.dart';


void main() => runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => RongImProvider()),
        ChangeNotifierProvider(create: (_) => ActiveProvider()),
        ChangeNotifierProvider(create: (_) => LoginProvider()),
        ChangeNotifierProvider(create: (_) => AdminProvide()),
        ChangeNotifierProvider(create: (_) => AppUserProvide()),
        ChangeNotifierProvider(create: (_) => AttributeProvide()),
        ChangeNotifierProvider(create: (_) => GiftProvider()),
        ChangeNotifierProvider(create: (_) => ReportProvider()),
        ChangeNotifierProvider(create: (_) => HeaderPortraitProvider()),
        ChangeNotifierProvider(create: (_) => ActiveProvider()),
        ChangeNotifierProvider(create: (_) => TempProvider()),
        ChangeNotifierProvider(create: (_) => BrushProvider()),
        ChangeNotifierProvider(create: (_) => RealNameProvider()),
      ],
      child: MyApp(),
    )
);

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  AppLifecycleState currentState = AppLifecycleState.resumed;
  bool isRunApp = true; // 默认应用是在前台
  var mianTheme;

  @override
  void initState() {
    super.initState();
//    mianTheme = Provider.of<LoginProvider>(context,listen: false).themeData;

    WidgetsBinding.instance.addObserver(this);
    print('');
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('app_icon');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onSelectNotification);

    prefix.RongcloudImPlugin.onMessageReceivedWrapper = (prefix.Message msg, int left, bool hasPackage, bool offline) {
      String hasP = hasPackage ? "true":"false";
      String off = offline ? "true":"false";
      print("  main里面的数据 object onMessageReceivedWrapper objName:"+msg.content.getObjectName()+" msgContent:"+msg.content.encode()+" left:"+left.toString()+" hasPackage:"+hasP+" offline:"+off);
      Provider.of<RongImProvider>(context,listen: false).getConversionList(); // 获取到消息更新一次会话列表03/03
      if(currentState == AppLifecycleState.paused) {
        print('引用到后台了，所以采用本地推送');
        _postLocalNotification(msg,left);
      }else {
        //通知其他页面收到消息
        EventBus.instance.commit(EventKeys.ReceiveMessage, {"message":msg,"left":left,"hasPackage":hasPackage});
      }
    };
    prefix.RongcloudImPlugin.onDataReceived = (Map map) {
      print(" 另外一个获取到消息的onDataReceived" + map.toString());
    };
  }


  Future onSelectNotification(String payload) {
    print('点击后先随便打印点东西');
  }


  // 本地通知
  void _postLocalNotification(prefix.Message msg, int left) async {
    var android = new AndroidNotificationDetails('channel id', 'channel NAME', 'CHANNEL DESCRIPTION', priority: Priority.High,importance: Importance.Max);
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
        1, '圈你客服', '你有新的消息了', platform,
        payload: 'kkwkkw');

//    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
//    var initializationSettingsAndroid =
//    new AndroidInitializationSettings("app_icon");// app_icon 所在目录为 res/drawable/
//
//    var initializationSettingsIOS = new IOSInitializationSettings(requestAlertPermission: true,requestSoundPermission: true);
//    var initializationSettings = new InitializationSettings(
//        initializationSettingsAndroid,initializationSettingsIOS);
//    flutterLocalNotificationsPlugin.initialize(initializationSettings,
//        onSelectNotification: null);
//
//    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
//    'your channel id', 'your channel name', 'your channel description',
//    importance: Importance.Max, priority: Priority.High, ticker: '本地通知');
//
//
//    var platformChannelSpecifics = NotificationDetails(
//    androidPlatformChannelSpecifics, null);
//
//    String content = "测试本地通知";
//
//    await flutterLocalNotificationsPlugin.show(1, 'RongCloud IM', content, platformChannelSpecifics, payload: 'item x');
  }




  @override
  Widget build(BuildContext context) {
    return Consumer<LoginProvider> (
      builder: (context,data,_) {
        return MaterialApp(
          onGenerateRoute: onGenerateRoute,
          theme: mianTheme,
          home: Login(),
        );
      },
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("--" + state.toString());
    currentState = state;
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed:// 应用程序可见，前台
        print('应用在前台运行');
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        print('进入到后台了');
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}